const router = require('express').Router()
const { chkToken, createLiveUrl } = require('../../util')
const {query} = require('../../db')
const moment = require('moment')
const { live } = require('../../config')

const tableName = 'rooms'

router.get('/', async (req, res, next)=>{
    let categories = await query('SELECT * FROM categories').catch(next)
    if(categories === undefined) return

    for(let i=0; i<categories.length; i++) {

        categories[i].rooms = await query('SELECT id,room_name,room_introduce,logo FROM rooms WHERE category_id=?', categories[i].id)
    }

    res.json({
        'ok': 1,
        'data': categories
    })
})

router.get('/playing', async (req, res, next)=>{
    let rooms = await query('SELECT a.pull_url,b.id FROM lives a LEFT JOIN rooms b ON a.user_id=b.user_id ORDER BY a.addtime DESC LIMIT 1').catch(next)
    if(rooms === undefined) return

    res.json({
        'ok': 1,
        'data': rooms[0]
    })
})

router.post('/live', chkToken, async (req, res, next)=>{

    let liveInfo = await query(`SELECT * FROM lives WHERE user_id=?`, req.userId).catch(next)
    if(liveInfo === undefined) return

    let timestamp = moment().unix()

    if(liveInfo.length === 0) {
        let url = createLiveUrl()
        let data = {
            user_id: req.userId,
            addtime: timestamp,
            push_url: url.push_url,
            pull_url: url.pull_url
        }
        
        let roomLogo = live.oss + '/czqclive/'+url.stream_name+'.jpg'

        let ret = await query('INSERT INTO lives SET ?', data).catch(next)
        if(ret === undefined) return

        ret = await query('UPDATE rooms SET logo = ? WHERE user_id = ?', [roomLogo, req.userId]).catch(next)
        if(ret === undefined) return

        res.json({
            'ok': 1,
            'data': {
                ...url
            }
        })
    } else {
        if(timestamp - liveInfo[0].addtime < 1500) {
            res.json({
                'ok': 1,
                'data': {
                    push_url: liveInfo[0].push_url,
                    pull_url: liveInfo[0].pull_url,
                }
            })
        } else {
            let url = createLiveUrl(req.userId)
            let data = {
                user_id: req.userId,
                addtime: timestamp,
                push_url: url.push_url,
                pull_url: url.pull_url
            }

            let roomLogo = live.oss + '/czqclive/'+url.stream_name+'.jpg'

            let ret = await query('UPDATE lives SET ? WHERE user_id=?', [data, req.userId]).catch(next)
            if(ret === undefined) return

            ret = await query('UPDATE rooms SET logo = ? WHERE user_id = ?', [roomLogo, req.userId]).catch(next)
            if(ret === undefined) return

            res.json({
                'ok': 1,
                'data': {
                    ...url
                }
            })
        }
    }

    
})

router.post('/', chkToken, async (req, res, next)=>{
    let room_name = req.body.room_name
    let room_introduce = req.body.room_introduce
    let category_id = req.body.category_id

    let sql = 'SELECT id,room_id FROM users WHERE id=?'
    let ret = await query(sql, req.userId).catch(next)
    if(ret === undefined) return 

    if(ret[0].room_id > 0) return next('您已经创建过房间了')

    let data = {
        room_name,
        room_introduce,
        category_id,
        user_id: req.userId,
        addtime: moment().unix()
    }

    sql = `INSERT INTO ${tableName} SET ?`
    ret = await query(sql, data).catch(next)
    if(ret === undefined) return 

    let room_id = ret.insertId
    ret = await query('UPDATE users SET room_id=? WHERE id=?', [ret.insertId, req.userId]).catch(next)
    if(ret === undefined) return

    res.json({
        'ok': 1,
        'data': {
            room_id
        }
    })
})

router.get('/:id', async (req, res, next)=>{
    let id = req.params.id

    let sql = `SELECT a.id,a.room_name,a.room_introduce,a.addtime,a.user_id,b.name,b.avatar,c.pull_url
                FROM ${tableName} a
                 LEFT JOIN users b ON a.user_id=b.id 
                 LEFT JOIN lives c ON a.user_id=c.user_id
                WHERE a.id = ?`
    let ret = await query(sql, id).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1,
        'data': ret[0]
    })
})

module.exports = router